package com.example.springboot.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.Result;
import com.example.springboot.service.impl.OrdersServiceImpl;
import com.example.springboot.service.impl.StoreServiceImpl;
import com.example.springboot.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺表(Store)表控制层
 *
 * @author makejava
 * @since 2024-01-13 17:16:26
 */
@RestController
@RequestMapping("/store")
public class StoreController {
    /**
     * 服务对象
     */
    @Autowired
    private StoreServiceImpl storeService;
    @Autowired
    private OrdersServiceImpl ordersService;


    /**
     * 获取所有商家信息
     *
     * @return
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        return Result.success(storeService.selectAll());
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        storeService.deleteById(id);
        return Result.success("删除成功!");
    }

    /**
     * 更新商家信息
     *
     * @param store
     * @return
     */
    @PutMapping("/updateById")
    public Result updateById(@RequestBody Store store) {
        storeService.updateById(store);
        return Result.success("更新成功！");
    }


    /**
     * 条件查询
     *
     * @param username
     * @param name
     * @param phone
     * @param status
     * @return
     */
    @GetMapping("/selectByManyCondition")
    public Result selectByManyCondition(@RequestParam("username") String username,
                                        @RequestParam("name") String name,
                                        @RequestParam("phone") String phone,
                                        @RequestParam("status") Integer status) {
        return Result.success(storeService.selectByManyCondition(username, name, phone, status));
    }


//    /**
//     * 条件查询  分页
//     * @param currentPage
//     * @param pageSize
//     * @param username
//     * @param name
//     * @param phone
//     * @param email
//     * @return
//     */
//    @GetMapping("/selectByManyConditionInpage")
//    public Result selectByManyConditionInpage(@RequestParam("currentPage") Integer currentPage,
//                                              @RequestParam("pageSize") Integer pageSize,
//                                              @RequestParam("username") String username,
//                                              @RequestParam("name") String name,
//                                              @RequestParam("phone") String phone,
//                                              @RequestParam("email") String email){
//        try {
//            return Result.success(storeService.selectByManyConditionInpage(currentPage,pageSize,username,name,phone,email));
//        }catch (Exception e){
//            return  Result.error("查询失败！  ----->    " + e.getMessage());
//        }
//    }

    /**
     * 条件查询  分页
     *
     * @param currentPage
     * @param pageSize
     * @param username
     * @param name
     * @param phone
     * @param status
     * @return
     */
    @GetMapping("/selectByManyConditionInpage")
    public Result selectByManyConditionInpage(@RequestParam("currentPage") Integer currentPage,
                                              @RequestParam("pageSize") Integer pageSize,
                                              @RequestParam("username") String username,
                                              @RequestParam("name") String name,
                                              @RequestParam("phone") String phone,
                                              @RequestParam("status") Integer status) {
        return Result.success(storeService.selectByManyConditionInpage(currentPage, pageSize, username, name, phone, status));
    }

    /**
     * 条件查询  分页
     *
     * @param currentPage
     * @param pageSize
     * @param username
     * @param name
     * @param phone
     * @return
     */
    @GetMapping("/selectByManyConditionNoStatusInpage")
    public Result selectByManyConditionNoStatusInpage(@RequestParam("currentPage") Integer currentPage,
                                                      @RequestParam("pageSize") Integer pageSize,
                                                      @RequestParam("username") String username,
                                                      @RequestParam("name") String name,
                                                      @RequestParam("phone") String phone) {
        return Result.success(storeService.selectByManyConditionNoStatusInpage(currentPage, pageSize, username, name, phone));
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam("currentPage") Integer currentPage,
                               @RequestParam("pageSize") Integer pageSize) {
        return Result.success(storeService.selectByPage(currentPage, pageSize));
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/deleteByIds")
    public Result deleteByIds(@RequestBody List<Integer> ids) {
        storeService.deleteByIds(ids);
        return Result.success("删除成功！");
    }


    /**
     * 添加店铺
     *
     * @param store
     * @return
     */
    @PostMapping("/addStore")
    public Result addStore(@RequestBody Store store) {
        storeService.addStore(store);
        return Result.success("添加成功！");
    }


    /**
     * 店铺详情
     *
     * @param id
     * @return
     */
    @GetMapping("/storeInfo")
    public Result storeInfo(@RequestParam("id") Integer id) {
        return Result.success(storeService.selectSimpleById(id));
    }


    /**
     * 加载所有的商家
     *
     * @return
     */
    @GetMapping("/loadAllStore")
    public Result loadAllStore() {
        return Result.success(storeService.loadAllStore());
    }

    @PostMapping("/getTotal")
    public Result getTotal() {
        return Result.success(storeService.getTotal());
    }

    @GetMapping("/storeTop10")
    public Result storeTop10() {
        return Result.success(storeService.storeTop10());
    }


    /**
     * 折线统计图
     *
     * @return
     */
    @GetMapping("/lineCharts")
    public Result lineCharts(@RequestParam("id") Integer id) {
        // 尝试获取订单服务
        try {
            // 获取最近一周内的所有订单
            List<Orders> list = ordersService.selectStoreRecentWeek(id);

            List<String> dateList = DateUtil.getRecentDaysAsString(7);
            // 对日期进行排序
            dateList.sort(Comparator.naturalOrder());
            // 创建折线列表
            List<Dict> lineList = new ArrayList<>();
            // 遍历日期列表
            for (String date : dateList) {

                Date startTime = DateUtil.getTodayStartTime(date);
                Date endTime = DateUtil.getTodayEndTime(date);


                // 计算每天订单的金额总和
                BigDecimal price = list.
                        stream().
                        filter(orders -> orders.getCreateTime().after(startTime) && orders.getCreateTime().before(endTime)).
                        map(Orders::getPayment).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
                // 计算每天订单的数量
                Long count = list.
                        stream().
                        filter(orders -> orders.getCreateTime().after(startTime) && orders.getCreateTime().before(endTime))
                        .count();

                // 计算每天订单的用户数量
                Integer userCount = list.stream()
                        .filter(orders -> orders.getCreateTime().after(startTime) && orders.getCreateTime().before(endTime))
                        .map(Orders::getUserId).
                        collect(Collectors.toSet()).size();
                // 创建字典
                Dict dict = Dict.create();
                // 将日期和金额总和放入字典
                Dict line = dict.set("date", date)
                        .set("price", price)
                        .set("count", count)
                        .set("userCount", userCount);
                // 将字典添加到折线列表
                lineList.add(line);
            }
            // 返回折线统计图数据
            return Result.success(lineList);
        } catch (Exception e) {
            throw new RuntimeException("请求折线统计图数据失败");
        }
    }


    @PostMapping("/getTodayInfo")
    public Result getTodayInfo(@RequestParam("id") Integer id) {
        return Result.success(storeService.getTodayInfo(id));
    }

    @GetMapping("/productCharts")
    public Result productCharts(@RequestParam("id") Integer id) {
        return Result.success(storeService.productCharts(id));
    }


    @PostMapping("/loadStoreInfoById")
    public Result loadStoreInfoById(@RequestParam("id") Integer id) {
        return Result.success(storeService.selectById(id));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param account
     * @param request
     * @return
     */
    @PutMapping("/changePassword")
    public Result changePassword(@RequestBody Account account, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        String id;
        try {
            id = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException("401", "请登录");
        }
        account.setId(Integer.valueOf(id));
        account.setToken(token);
        storeService.changePassword(account);
        return Result.success();
    }

}

